package com.masonluo.mlonlinejudge.controller;

import com.masonluo.mlonlinejudge.mapper.IndexMapper;
import com.masonluo.mlonlinejudge.model.bo.IndexBo;
import com.masonluo.mlonlinejudge.model.param.IndexParam;
import com.masonluo.mlonlinejudge.model.vo.IndexVo;
import com.masonluo.mlonlinejudge.result.Result;
import com.masonluo.mlonlinejudge.service.IndexService;
import com.masonluo.mlonlinejudge.utils.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author masonluo
 * @date 2021/2/11 12:35 下午
 */
@RestController
@RequestMapping("/index")
public class IndexController {


    @Autowired
    private IndexService indexService;

    @Autowired
    private IndexMapper indexMapper;


    @GetMapping
    public Result<List<IndexVo>> listAll() {
        return Result.ok(indexMapper.boToVo(indexService.listAll()));
    }


    @PostMapping
    public Result<IndexVo> add(@RequestParam("name") String name,
                               @RequestParam("order") Integer order,
                               @RequestParam("bookId") Integer bookId) {
        if (StringUtils.isBlank(name)) {
            throw new IllegalArgumentException("The name should not be empty");
        }

        if (order == null || order <= 0) {
            throw new IllegalArgumentException("The order should be larger than 0");
        }

        IndexBo bo = indexService.createIndex(bookId, name, order);
        return Result.created(indexMapper.boToVo(bo));
    }


    @PutMapping()
    public Result update(@RequestBody @Valid IndexParam param) {
        indexService.update(param);
        return Result.ok();
    }


    @DeleteMapping("/{index_id}")
    public Result delete(@PathVariable("index_id") Integer indexId) {
        indexService.deleteById(indexId);
        return Result.ok();
    }
}
